using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Abp.Application.Services.Dto;
using Abp.AspNetCore.Mvc.Authorization;
using Abp.AspNetCore.Mvc.Extensions;
using Abp.Domain.Repositories;
using FwProject.Comm.ExcelUtil;
using FwProject.Controllers;
using FwProject.Core.Distribution;
using FwProject.Core.Restaurant;
using FwProject.Distribution;
using FwProject.FactoryInfo;
using FwProject.Net.MimeTypes;
using FwProject.Restaurant;
using FwProject.Restaurant.Dto;
using FwProject.TypeNumber;
using FwProject.Users;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;

namespace FwProject.Web.Controllers
{

    public class RestaurantController : FwProjectControllerBase
    {
        private readonly IRestaurantAppService _restaurantAppService;
        private readonly ITypeNumberInfoAppService _typeNumberInfoAppService;
        private readonly IRestaurantTypeNumberAppService _restaurantTypeNumberAppService;
        private readonly IFactoryNameInfoAppService _factoryNameInfoAppService;
        private readonly IUserAppService _userAppService;
        private readonly IStockCheckInfoAppService _stockCheckInfoAppService;
        private readonly IDistributionDetailsAppService _distributionDetailsAppService;
        private readonly IHostingEnvironment _env;
        private readonly IRepository<DistributionInfoDetails, Guid> _repositoryDistributionInfoDetails;

        public RestaurantController(IRestaurantAppService restaurantAppService, IHostingEnvironment env, ITypeNumberInfoAppService typeNumberInfoAppService, IUserAppService userAppService, IStockCheckInfoAppService stockCheckInfoAppService,
            IRestaurantTypeNumberAppService restaurantTypeNumberAppService, IFactoryNameInfoAppService factoryNameInfoAppService,
            IRepository<DistributionInfoDetails, Guid> repositoryDistributionInfoDetails, IDistributionDetailsAppService distributionDetailsAppService)
        {
            _repositoryDistributionInfoDetails = repositoryDistributionInfoDetails;
            _restaurantTypeNumberAppService = restaurantTypeNumberAppService;
            _restaurantAppService = restaurantAppService;
            _env = env;
            _typeNumberInfoAppService = typeNumberInfoAppService;
            _factoryNameInfoAppService = factoryNameInfoAppService;
            _userAppService = userAppService;
            _stockCheckInfoAppService = stockCheckInfoAppService;
            _distributionDetailsAppService = distributionDetailsAppService;
        }


        #region 视图
        /// <summary>
        /// 餐厅管理
        /// </summary>
        /// <param name="id"></param>
        /// <param name="factoryid"></param>
        /// <param name="keyword"></param>
        /// <returns></returns>
        public async Task<ActionResult> Index(int id, int size, long? DriverId, string factoryid = "", string keyword = "")
        {
            if (id == 0)
                id = 1;

            if (size == 0)
                size = 20;

            if (Request.IsAjaxRequest())
            {
                var restaurant = await _restaurantAppService.GetAllPagedListAsync(id, size, factoryid, keyword, DriverId, null);
                return PartialView("IndexPartial", restaurant);
            }
            return View();

        }
        /// <summary>
        /// 餐厅新增统计
        /// </summary>
        /// <param name="pageIdx"></param>
        /// <param name="beginTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public async Task<ActionResult> RestaurantNewAdd(int pageIdx, int size, DateTime? beginTime, DateTime? endTime)
        {
            if (pageIdx == 0)
                pageIdx = 1;
            if (size == 0)
                size = 20;

            if (Request.IsAjaxRequest())
            {
                var restaurant = await _restaurantAppService.GetNewAddPagedListAsync(pageIdx, size, beginTime, endTime);
                return PartialView("RestaurantNewAddPartial", restaurant);
            }
            return View();

        }
        /// <summary>
        /// 餐厅停用统计
        /// </summary>
        /// <param name="pageIdx"></param>
        /// <param name="beginTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public async Task<ActionResult> Discontinuation(int pageIdx, int size, DateTime? beginTime, DateTime? endTime)
        {
            if (pageIdx == 0)
                pageIdx = 1;
            if (size == 0)
                size = 20;
            var restaurant = await _restaurantAppService.GetDiscontinuationPagedListAsync(pageIdx, size, beginTime, endTime);
            if (Request.IsAjaxRequest())
            {

                return PartialView("DiscontinuationPartial", restaurant);
            }
            return View(restaurant);

        }

        /// <summary>
        /// 餐厅分配
        /// </summary>
        /// <param name="id"></param>
        /// <param name="keyword"></param>
        /// <returns></returns>
        //public async Task<ActionResult> Distribution(int id, string keyword = "")
        //{
        //    if (id == 0)
        //        id = 1;

        //    var restaurant = await _restaurantAppService.GetUnassignedsAsync(id, 15, keyword);
        //    if (Request.IsAjaxRequest())
        //    {
        //        return PartialView("DistributionPartial", restaurant);
        //    }
        //    return View(restaurant);

        //}

        /// <summary>
        /// 添加餐厅
        /// </summary>
        /// <returns></returns>
        public async Task<ActionResult> Create(Guid? factoryinfoId)
        {
            var list = await _typeNumberInfoAppService.GetAllTypeNumber();
            ViewBag.TypeNumbers = list.Select(o => new SelectListItem() { Text = o.Name, Value = o.Id.ToString() });
            ViewBag.FactoryinfoId = factoryinfoId;
            return View(new RestaurantInputDto());
        }

        /// <summary>
        /// 修改餐厅
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ActionResult> Edit(Guid id, Guid? factoryinfoId)
        {
            var entity = await _restaurantAppService.GetByEnterIdAsync(id);
            var list = await _typeNumberInfoAppService.GetAllTypeNumber();
            ViewBag.TypeNumbers = list.Select(o => new SelectListItem() { Text = o.Name, Value = o.Id.ToString() });
            ViewBag.FactoryinfoId = factoryinfoId;
            ViewBag.Id = id;
            return View(entity);
        }

        /// <summary>
        /// 分配工厂
        /// </summary>
        /// <returns></returns>
        //public IActionResult Assignment()
        //{
        //    return View();
        //}
        #endregion



        #region 操作
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> CreateRestaurant(RestaurantInputDto input)
        {
            var id = await _restaurantAppService.Create(input);
            return Json(id);

        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="id"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> EditRestaurant(Guid id, RestaurantInputDto input)
        {
            await _restaurantAppService.Update(id, input);
            return Json(id);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<JsonResult> DeleteRestaurant(Guid id)
        {
            await _restaurantAppService.DeleteAsync(id);
            return Json(id);
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> FileSave()
        {
            var date = Request;
            var files = Request.Form.Files;
            long size = files.Sum(f => f.Length);
            string webRootPath = _env.WebRootPath;
            string contentRootPath = _env.ContentRootPath;
            foreach (var formFile in files)
            {
                if (formFile.Length > 0)
                {
                    string[] st = formFile.FileName.Split('.');
                    int length = st.Count();
                    string fileExt = st[length - 1]; //文件扩展名，不含“.”
                    long fileSize = formFile.Length; //获得文件大小，以字节为单位
                    string newFileName = System.Guid.NewGuid().ToString() + "." + fileExt; //随机生成新的文件名
                    var filePath = webRootPath + "/upload/" + newFileName;
                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {

                        await formFile.CopyToAsync(stream);
                    }
                }
            }

            return Ok(new { count = files.Count, size });
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UploadImage()
        {
            return Json(base.UploadFile(_env, Request.Form.Files, RestaurantInfo.TempFileUrlPrefix));
        }

        [HttpPost]
        public async Task<JsonResult> UploadExcel(Guid id)
        {
            string FilePath = base.GetUploadFileToFilePath(_env, Request.Form.Files, RestaurantInfo.SaveFileUrlExcelPrefix);
            /// 添加一个服务接受上传后的excel文件路径
            /// 创建一个导入属性类 类型类的属性名和excel 第一行的列名一样
            ///服务创建一个方法返回数据源 List<RestaurantInfo> list =ExcExcelImportelUtil<RestaurantInfo>.GetExcelToList(FilePath);
            ///

            List<ExcelImportRetaurant> list = ExcExcelImportelUtil<ExcelImportRetaurant>.GetExcelToList(FilePath);
            var result = await _restaurantAppService.ExcelImportAsync(list, id);

            return Json(result);
        }
        /// <summary>
        /// 餐厅Excel导入模板下载
        /// </summary>
        /// <returns></returns>
        public IActionResult DownLoadExcel()
        {
            List<ExcelImportRetaurant> list = new List<ExcelImportRetaurant>();
            ExcelImportRetaurant model = new ExcelImportRetaurant()
            {
                RestaurantName = "",
                RestaurantContact = "",
                BalanceCycle = "",
                BalanceWay = "",
                ChargeWay = "",
                RestaurantAdderss = "",
                Deposit = "",
                DepositDate = "",
                DriverName = "",
                Mobile = "",
                Price = "",
                TypeNumberName = ""
            };
            list.Add(model);
            ExcelHelper helper = new ExcelHelper();
            if (!Directory.Exists(Path.Combine(_env.WebRootPath, $"Excel")))
                Directory.CreateDirectory(Path.Combine(_env.WebRootPath, $"Excel"));

            var path = Path.Combine(_env.WebRootPath, "Excel\\餐厅Excel导入模板.xlsx");
            helper.OutDataToExcel(list, path);
            var stream = System.IO.File.OpenRead(path);
            return File(stream, MimeTypeNames.ApplicationOctetStream, "餐厅Excel导入模板.xlsx");
        }

        /// <summary>
        /// 餐厅列表Excel导出
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> ExportExcel()
        {
            var list = await _restaurantAppService.GetRestaurantListAsync();
            return DoExcel<RestaurantOutputDto>(list, _env);

        }
        /// <summary>
        /// 餐厅新增统计导出
        /// </summary>
        /// <param name="beginTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public async Task<IActionResult> ExportNewAddRestaurant(DateTime? beginTime, DateTime? endTime)
        {
            var list = await _restaurantAppService.GetRestaurantNewAddAsync(beginTime, endTime);
            return DoExcel<RestaurantOutputDto>(list, _env);
        }
        /// <summary>
        /// 餐厅停用统计导出
        /// </summary>
        /// <param name="beginTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public async Task<IActionResult> ExportDiscontinuation(DateTime? beginTime, DateTime? endTime)
        {
            var list = await _restaurantAppService.GetDiscontinuationListAsync(beginTime, endTime);
            return DoExcel<RestaurantOutputDto>(list, _env);
        }
        #endregion

        public IActionResult TestImage()
        {
            return View("UploadImage");
        }

        /// <summary>
        /// 分配工厂
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ActionResult> Factory(int id, string RestaurantName)
        {
            if (id == 0)
                id = 1;
            var restaurant = await _restaurantAppService.GetRestaurantPagedListAsync(id, 20, RestaurantName);
            if (Request.IsAjaxRequest())
            {
                return PartialView("FactoryPartial", restaurant);
            }
            return View(restaurant);

        }

        public async Task<ActionResult> EditFactory(Guid id)
        {
            var factory = await _factoryNameInfoAppService.GetAllAsync("");
            ViewBag.Factory = factory.Select(c => new SelectListItem() { Value = c.Id.ToString(), Text = c.FactoryName });

            var model = await _restaurantAppService.GetByIdAsync(id);
            return View(model);
        }

        [HttpPost]
        public async Task<JsonResult> EditRestaurantByFactory(Guid id, Guid FactoryInfoId)
        {
            await _restaurantAppService.EditRestaurantByFactory(id, FactoryInfoId);
            return Json(id);
        }

        public IActionResult Distributed()
        {
            return View();
        }

        public async Task<IActionResult> GetRestaurantDistributedData(Guid? id, string keyword = "")
        {
            var data = await _restaurantAppService.GetRestaurantDistributedAsync(id, keyword);
            return Json(data);
        }
        public async Task<IActionResult> GetRestaurantAdvancePaymentData(Guid? id)
        {
            var data = await _restaurantAppService.GetRestaurantAdvancePaymentAsync(id);
            return Json(data);
        }

        #region 餐厅店存统计
        /// <summary>
        /// 餐厅店存统计
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> RestaurantStock(int pageIdx, int size, string RestaurantName, string DriverName)
        {
            if (pageIdx == 0)
                pageIdx = 1;
            if (size == 0)
                size = 20;
            var model = await _restaurantAppService.GetRestaurantStockAsync(pageIdx, size, RestaurantName, DriverName);
            if (Request.IsAjaxRequest())
            {
                return PartialView("RestaurantStockPartial", model);
            }
            return View(model);
        }
        /// <summary>
        /// 餐厅店存统计导出
        /// </summary>
        /// <param name="RestaurantName"></param>
        /// <param name="DriverName"></param>
        /// <returns></returns>
        public async Task<IActionResult> ExportRestaurnatStock(string RestaurantName, string DriverName)
        {
            var list = await _restaurantAppService.GetExportRestaurantStockAsync(RestaurantName, DriverName);
            return DoExcel<RestaurantStockDto>(list, _env);
        }
        #endregion


        #region 对账单
        /// <summary>
        /// 对账单
        /// </summary>
        public async Task<IActionResult> StatementAccount(int pageIdx, int size, string RestaurantName, string DriverName)
        {
            if (pageIdx == 0)
                pageIdx = 1;

            if (size == 0)
                size = 20;
            var model = await _restaurantAppService.GetRestaurantStockAsync(pageIdx, size, RestaurantName, DriverName);
            if (Request.IsAjaxRequest())
            {
                return PartialView("StatementAccountPartial", model);
            }
            return View(model);
        }

        #endregion

        /// <summary>
        /// 餐厅配送详情
        /// </summary>
        public async Task<IActionResult> RestaurantDistributionDetails(int pageIdx, int size, Guid id, DateTime? beginTime, DateTime? endTime)
        {
            if (pageIdx == 0)
                pageIdx = 1;
            if (size == 0)
                size = 20;
            var restaurant = await _restaurantAppService.GetByIdAsync(id);
            ViewBag.RestaurantName = restaurant.RestaurantName;
            var model = await _restaurantAppService.GetRestaurantDetailsPagedListAsync(pageIdx, size, id, beginTime, endTime);
            if (Request.IsAjaxRequest())
            {
                return PartialView("RestaurantDistributionDetailsPartial", model);
            }
            return View(model);
        }

        public async Task<JsonResult> GetSuggestData()
        {
            var restaurant = await _restaurantAppService.GetRestaurantListAsync();
            return Json(restaurant);
        }

        public async Task<IActionResult> GetRestaurantTypeNumberCount(Guid id)
        {

            var model = await _restaurantAppService.GetByIdAsync(id);

            return Json(model.RealStock);
        }
        /// <summary>
        /// 店存盘点
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> RestaurantStockCheck()
        {
            var usermodel = await _userAppService.GetAllPersonAsync();
            ViewBag.Person = usermodel;
            return View();
        }
        [HttpPost]
        public async Task<JsonResult> RestaurantStockCheck(StockCheckInput input)
        {
            await _stockCheckInfoAppService.Create(input);
            return Json(1);
        }
    }
}
